<template>
    <div class="search-container">
        <form action="/" class="search-form">
        <van-search
            v-model="searchText"
            show-action
            placeholder="请输入搜索关键词"
            background="#3296fa"
            @search="onSearch"
            @cancel="onCancel"
            @focus="isSearchEdit=false"
        />
        </form>

        <SearchResult v-if="isSearchEdit"
        :searchText="searchText"/>

        <SearchSuggestion v-else-if="searchText" 
        :searchText="searchText"
        @searchSuggestionEmit="onSearch"
        />

        <SearchHistory v-else
        :historySearchs="historySearchs"
        @searchHistory="onSearch"
        @clear-search-history="historySearchs=[]"
        />
    </div>
</template>

<script>
import SearchHistory from './component/search-history.vue';
import SearchSuggestion from './component/search-suggestion.vue';
import SearchResult from './component/search-result.vue';
import { getItem, setItem } from '@/utils/storage';

export default {
    components() {
        SearchHistory,
        SearchSuggestion,
        SearchResult;
    },
    data() {
        return {
            searchText: "",
            isSearchEdit: false,
            historySearchs: getItem('TOUTIAO_SEARCH_HISTORY') || []
        };
    },
    
    components: { SearchHistory, SearchSuggestion, SearchResult },
    // watch: {
    //     historySearchs: {
    //         handler(vla) {
    //             console.log('检查',val);
    //         }
    //     }
    //     // historySearchs(val) {
    //     //     console.log('检查',val);
    //     //     setItem('TOUTIAO_SEARCH_HISTORY',val)
    //     // }
    // },
    /////zhangya  为啥监听不到
    watch: {  
        historySearchs: {
            // handler(val) {
                // this.loadSearchKeysSuggestions(val)
                // clearTimeout(timer)
                // this.fangdou(val)
            // },
            // immediate:true
        // }
            handler (val) {
                console.log('检查',val);
            }
        }
    },
    methods: {
        onSearch(val) {
            this.searchText = val
            this.isSearchEdit = true
            const index = this.historySearchs.indexOf(val);
            if (index !== -1) {
                this.historySearchs.splice(index, 1)
            }
            this.historySearchs.unshift(val)
        },
        onCancel() {
            this.$router.back()
        }
    }
}
</script>

<style lang="less" scoped>

.search-container {
    padding-top: 54px;
    :deep(.van-search) {
        .van-search__action {
            color: #fff;
        }
        
    }
    .search-form {
            position: fixed;
            top: 0;
            left: 0;
            right: 0;
            z-index: 1;
        }

}
</style>